package cn.xuchunh.okhttpdemo;

import android.content.Context;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.squareup.okhttp.OkHttpClient;

import java.util.Map;

/**
 *
 * Created by Administrator on 2015/12/28.
 */
public class VolleyHttpManager {

    private static VolleyHttpManager instance;
    private RequestQueue requestQueue;

    private VolleyHttpManager(Context context) {
        requestQueue = Volley.newRequestQueue(context.getApplicationContext(), new OkHttpStack2(new OkHttpClient()));
        requestQueue.start();
    }

    public synchronized static VolleyHttpManager getInstance(Context context) {
        if(instance == null){
            instance = new VolleyHttpManager(context);
        }
        return instance;
    }

    public synchronized void close(){
        if(requestQueue != null){
            requestQueue.stop();
            requestQueue = null;
            instance = null;
        }
    }

    public void get(String url, Response.Listener<String> listener, Response.ErrorListener errorListener){
        StringRequest request = new StringRequest(Request.Method.GET, url, listener, errorListener);
        requestQueue.add(request);
    }

    public void post(String url, Response.Listener<String> listener, Response.ErrorListener errorListener, final Map<String, String> params){
        StringRequest request = new StringRequest(Request.Method.POST, url, listener, errorListener){
            /**
             * Returns a Map of parameters to be used for a POST or PUT request.  Can throw
             * {@link AuthFailureError} as authentication may be required to provide these values.
             * <p/>
             * <p>Note that you can directly override {@link #getBody()} for custom data.</p>
             *
             * @throws AuthFailureError in the event of auth failure
             */
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                return params == null ? super.getParams() : params;
            }
        };
        requestQueue.add(request);
    }

}
